import os

from sc_engine.apps import messages as msgs
from sc_engine.repositories import Repository, use
from sc_engine.repositories.stores import PickleFileStore

class CommentarySetData(object):
    """A set of videos_id's for videos designed to be watched in order

    Can add the video_ids one at a time, and handle cases where a part is not
    yet known by making it's video_id None
    """

    def __init__(self):
        self.video_ids = []

    def update_part(self, part_number, video_id):
        number_parts = len(self.video_ids)
        if number_parts < part_number:
            self.video_ids += [None] * (part_number - number_parts)

        self.video_ids[part_number - 1] = video_id

def make_app(app_name, root_config, config):
    store_filename = os.path.join(root_config['data_directory'], app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = CommentaryDataApp(repo)

    return {
        msgs.VideoGameLinkAnnouncement: app.video_game_link_announcement
    }

class CommentaryDataApp(object):
    """Collects and announces complete data on commentaries.

    Often times, a commentary is split into multiple parts. Each part is found
    individually, so this app listens for the various parts, and when it thinks
    it has all of them for a specific set, sends out a message stating the
    set's information.
    """
    def __init__(self, repo):
        self.repo = repo

    @use('repo', 'commentaries')
    def video_game_link_announcement(self, msg, commentaries):
        key = (msg.match_id, msg.game_number, msg.author)

        if key not in commentaries:
            commentaries[key] = CommentarySetData()

        commentaries[key].update_part(msg.part_number, msg.video_id)
        video_ids = commentaries[key].video_ids
        
        if None not in video_ids:
            new_msg = msgs.CommentarySetDataAnnouncement(msg.match_id,
                msg.game_number,
                msg.author,
                video_ids)

            return new_msg

